package network2;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoServer {
    private ServerSocket serverSocket = null;

    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动！");
        while (true){
            Socket clientSocket = serverSocket.accept();
            processConnection(clientSocket);
        }
    }

//    通过这个方法来处理联系
    private void processConnection(Socket clientSocket) throws IOException {
//        1.打印日志
        System.out.printf("%s:%d 客户端上线！\n",clientSocket.getInetAddress(),clientSocket.getPort());
//        2.从socket中获取流对象，来进行后续操作
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()){
//            3.循环，针对每个连接，客户端可能发送多个请求，服务器就要返回多个响应
            Scanner scanner = new Scanner(System.in);
            while(true){
//                3.1读取请求并解析
                if (!scanner.hasNext()){
                    System.out.printf("[%s:%d] 客户端下线\n", clientSocket.getInetAddress(), clientSocket.getPort());
                    break;
                }
                String request = scanner.next();
//                3.2根据请求计算响应
                String response = process(request);
//                3.3把响应写回给客户端
                outputStream.write(response.getBytes());
//                3.4服务器打印日志
                System.out.printf("[%s:%d] req=%s,resp=%s\n",clientSocket.getInetAddress(),clientSocket.getPort(),request,response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            clientSocket.close();
        }


    }

//    根据请求计算响应
//    回显服务器，所以直接将请求返回
    private String process(String request) {
        return request + "\n";
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer(9999);
        server.start();
    }
}
